package com.cskaoyan.controller.wx.search;

import com.cskaoyan.model.BaseParam;
import com.cskaoyan.model.BaseRespVo;
import com.cskaoyan.model.realm.WxLoginUserData;
import com.cskaoyan.model.wx.search.WxUser;
import com.cskaoyan.model.wx.search.vo.SearchIndexVO;
import com.cskaoyan.service.wx.Search.KeywordService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author AhaNg
 * @Date 2022/1/11 20:31
 * @description: 小程序首页搜索栏功能
 * @return:
 */
@RestController
@RequestMapping("wx/search")
public class WxSearchController {

    @Autowired
    KeywordService keywordService;

    /**
     * @Author: AhaNg
     * @description: 首页搜索功能，只有当用户登陆时显示搜索记录
     * @return:
     */
    @GetMapping("index")
    public BaseRespVo index() {
        Subject subject = SecurityUtils.getSubject();
        WxLoginUserData wxUser = (WxLoginUserData) subject.getPrincipal();
        Integer userId = null;
        //如果用户未登录
        if (wxUser != null) {
            userId = wxUser.getId();
        }
        SearchIndexVO searchIndexVO = keywordService.searchIndex(userId);
        return BaseRespVo.ok(searchIndexVO);
    }

    /**
     * @Author: AhaNg
     * @description: 搜索栏关键字提示，在确定了搜索键后，应该往用户历史搜索表中添加记录
     * @return:
     */

    @GetMapping("helper")
    public BaseRespVo helper(String keyword) {

        List<String> helperList = keywordService.helper(keyword);
        return BaseRespVo.ok(helperList);
    }

    /**
     * @Author: AhaNg
     * @description: 清除用户的搜索历史
     * @return:
     */
    @PostMapping("clearhistory")
    public BaseRespVo clearHistory() {
        Subject subject = SecurityUtils.getSubject();
        WxLoginUserData wxUser = (WxLoginUserData) subject.getPrincipal();
        if (wxUser == null) {
            return BaseRespVo.fail("请先登录");
        }
        keywordService.clearHistory(wxUser.getId());
        return BaseRespVo.ok();
    }

}
